package com.cherrish.demo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @author cherrish
 * @time 2019-02-27 14:20
 * @name TestThread5
 * @desc:
 */
public class TestThread5 {
    static class MyCallable implements Callable<Integer> {
        private final int i;

        public MyCallable(int i) {
            super();
            this.i = i;
        }

        @Override
        public Integer call() throws Exception {
// 返回一个值或受检查的异常
//throw new Exception();
            return new Integer(i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        java.util.concurrent.ExecutorService threadPoolExecutor =

                java.util.concurrent.Executors.newCachedThreadPool();

        java.util.concurrent.CompletionService<Integer> completionService =
                new java.util.concurrent.ExecutorCompletionService<Integer>(threadPoolExecutor);
        final int threadNum = 10;
        for (int i = 0; i < threadNum; i++) {
            completionService.submit(new MyCallable(i + 1));
        }
/**
  * 如果不再需要新任务，请适当关闭threadPoolExecutor并拒绝新任务
  */
        threadPoolExecutor.shutdown();
/**
  * 模拟其他业务逻辑
  */
        Thread.sleep(2000);
        for (int i = 0; i < threadNum; i++) {
            try {
                System.out.println("result========" + completionService.take().get());
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
